<script setup lang="ts">
import {ref, onMounted, onBeforeMount} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import type {FormInstance, FormRules} from 'element-plus'
import request from '@/utils/request';
import router from '@/router';

// 登录状态检查
onBeforeMount(async () => {
  try {
    // 尝试获取用户信息来验证登录状态
    await request.get('/user/info');
  } catch (error) {
    // 如果获取用户信息失败，说明未登录
    ElMessage.error('请先登录账号');
    router.push('/Login');
  }
})

/* 用户信息 */
const userInfo = ref({
  uid: '',
  username: '',
  phone: '',
  gender: '',
  address: ''
})

/* 表单引用 */
const usernameFormRef = ref<FormInstance>()
const phoneFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()
const genderFormRef = ref<FormInstance>()

/* 表单数据 */
//用户名称表单
const usernameForm = ref({
  username: ''
})
//用户电话号表单
const phoneForm = ref({
  phone: ''
})
//用户密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
//用户性别表单
const genderForm = ref({
  gender: ''
})

/* 表单验证规则 */
//用户名称规则
const usernameRules = ref<FormRules>({
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
  ]
})
//用户手机号规则
const phoneRules = ref<FormRules>({
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^[1][3,4,5,7,8][0-9]{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ]
})
//用户密码规则
const passwordRules = ref<FormRules>({
  oldPassword: [
    {required: true, message: '请输入原密码', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9_-]+$/, message: '只能包含字母、数字、下划线和连字符', trigger: 'blur'}
  ],
  newPassword: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9_-]+$/, message: '只能包含字母、数字、下划线和连字符', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请确认新密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})
// 用户性别规则
const genderRules = ref<FormRules>({
  gender: [
    {required: true, message: '请选择性别', trigger: 'change'}
  ]
})

/* 获取用户信息 */
const fetchUserInfo = async () => {
  try {
    // 从后端获取用户信息
    const response = await request.get('/user/info');
    console.log('用户信息:', response);
    const userData = response.data || response;
    let genderText = "";
    // 性别转换成中文
    switch (userData.userSex.toString()) {
      case "0":
        genderText = "女";
        break;
      case "1":
        genderText = "男";
        break;
      case "2":
        genderText = "保密";
        break;
      default:
        genderText = "未知";
    }
    userInfo.value = {
      uid: userData.userId,
      username: userData.userName,
      phone: userData.userPhone,
      gender: genderText,
    }
    // 初始化表单数据
    usernameForm.value.username = userInfo.value.username;
    phoneForm.value.phone = userInfo.value.phone;
    genderForm.value.gender = userInfo.value.gender;
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
}

/* 更改用户名 */
const updateUsername = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 发送更新用户名的请求
        const response = await request.post('/user/update', {
          userId: userInfo.value.uid,
          userName: usernameForm.value.username
        })
        ElMessage.success('用户名更新成功')
        // 用户名修改成功后注销用户
        try {
          await request.get('/user/logout');
        } catch (logoutError) {
          console.error('注销失败:', logoutError);
        }
        // 清除本地存储的用户信息和token
        localStorage.removeItem('satoken');
        localStorage.removeItem('userInfo');
        ElMessage.success('用户名修改成功，请重新登录');
        // 跳转到登录页面
        router.push('/Login');
      } catch (error) {
        console.error('更新用户名失败:', error)
        ElMessage.error('用户名更新失败')
      }
    }
  })
}

/* 更新手机号 */
const updatePhone = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 发送更新手机号的请求
        const response = await request.post('/user/update', {
          userId: userInfo.value.uid,
          userPhone: phoneForm.value.phone
        })
        ElMessage.success('手机号更新成功')
        // 手机号修改成功后注销用户
        try {
          await request.get('/user/logout');
        } catch (logoutError) {
          console.error('注销失败:', logoutError);
        }
        // 清除本地存储的用户信息和token
        localStorage.removeItem('satoken');
        localStorage.removeItem('userInfo');
        ElMessage.success('手机号修改成功，请使用"新手机号"重新登录!');
        // 跳转到登录页面
        router.push('/Login');
      } catch (error) {
        console.error('更新手机号失败:', error)
        ElMessage.error('手机号更新失败')
      }
    }
  })
}

/* 更新性别 */
const updateGender = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        //女返回"0"，男返回"1"，保密返回"2"，其余返回"3"
        const gender = genderForm.value.gender === '女' ? "0" :
            genderForm.value.gender === '男' ? "1" :
                genderForm.value.gender === '保密' ? "2" : "3";
        // 发送更新性别的请求
        const response = await request.post('/user/update', {
          userId: userInfo.value.uid,
          userSex: gender
        })
        ElMessage.success('性别更新成功')
        // 性别修改成功后注销用户
        try {
          await request.get('/user/logout');
        } catch (logoutError) {
          console.error('注销失败:', logoutError);
        }
        // 清除本地存储的用户信息和token
        localStorage.removeItem('satoken');
        localStorage.removeItem('userInfo');
        ElMessage.success('用户名修改成功，请重新登录');
        // 跳转到登录页面
        router.push('/Login');
      } catch (error) {
        console.error('更新性别失败:', error)
        ElMessage.error('性别更新失败')
      }
    }
  })
}

/* 更改密码 */
const updatePassword = async (formEl: FormInstance | undefined) => {
  //如果没有传入表单实例，函数直接返回，避免后续操作出错。
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        // 检查新密码是否与原密码相同
        if (passwordForm.value.oldPassword === passwordForm.value.newPassword) {
          ElMessage.error('新密码不能与原密码相同')
          return
        }
        //获取旧密码
        const response1 = await request.get('/user/info');
        console.log('用户旧密码:', response1);
        const userOldPasswordData = response1.data || response1;
        if (passwordForm.value.oldPassword === userOldPasswordData.userPassword) {
          // 旧密码正确，发送更新密码的请求
          const response2 = await request.post('/user/update', {
            userId: userInfo.value.uid,
            userPassword: passwordForm.value.newPassword
          });
          console.log('密码更新成功:', response2);
          // 密码修改成功后注销用户
          try {
            await request.get('/user/logout');
          } catch (logoutError) {
            console.error('注销失败:', logoutError);
          }
          // 清除本地存储的用户信息和token
          localStorage.removeItem('satoken');
          localStorage.removeItem('userInfo');
          ElMessage.success('密码修改成功，请重新登录');
          // 跳转到登录页面
          router.push('/Login');
        } else {
          ElMessage.error('旧密码错误');
        }
      } catch (error) {
        console.error('更新密码失败:', error)
        ElMessage.error('密码修改失败')
      }
    }
  })
}

// 删除账号
const deleteAccount = () => {
  ElMessageBox.confirm(
      '此操作将永久删除您的账号, 是否继续?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        try {
          await request.post('/user/delete', {
            userId: userInfo.value.uid
          })

          ElMessage.success('账号删除成功')
          // 账号删除成功后注销用户
          try {
            await request.get('/user/logout');
          } catch (logoutError) {
            console.error('注销失败:', logoutError);
          }
          // 清除本地存储的用户信息和token
          localStorage.removeItem('satoken');
          localStorage.removeItem('userInfo');
          ElMessage.success('账号删除成功，请重新登录');
          // 跳转到主页面
          router.push('/Homepage');
        } catch (error) {
          console.error('删除账号失败:', error)
          ElMessage.error('账号删除失败')
        }
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
}

/* 注销账号 */
const logout = async () => {
  ElMessageBox.confirm(
      '确定要注销当前账号吗？',
      '注销确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        try {
          await request.get('/user/logout');
        } catch (logoutError) {
          console.error('注销失败:', logoutError);
        }
        // 清除本地存储的用户信息和token
        localStorage.removeItem('satoken');
        localStorage.removeItem('userInfo');
        ElMessage.success('账号注销成功');
        // 跳转到主页面
        router.push('/Homepage');
      })
      .catch(() => {
        ElMessage.info('已取消注销');
      });
}


onMounted(() => {
  fetchUserInfo()
})
</script>

<template>
  <!-- 最外层容器 -->
  <div class="body">
    <!-- 左上角标题 -->
    <h1>我的账号</h1>
    <!-- 主体 -->
    <div class="Main">
      <!-- UID展示 -->
      <div class="accountUpdate">
        <h3>账号ID</h3>
        <div class="uid-display">
          <span>{{ userInfo.uid }}</span>
        </div>
      </div>

      <!-- 更改名称 -->
      <div class="accountUpdate">
        <h3>更改名称</h3>
        <el-form
            ref="usernameFormRef"
            :model="usernameForm"
            :rules="usernameRules"
            label-width="80px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
                v-model="usernameForm.username"
                style="width: 300px"
                placeholder="请输入用户名"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateUsername(usernameFormRef)">
              保存
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 更改手机号 -->
      <div class="accountUpdate">
        <h3>更改手机号</h3>
        <el-form
            ref="phoneFormRef"
            :model="phoneForm"
            :rules="phoneRules"
            label-width="80px"
        >
          <el-form-item label="手机号" prop="phone">
            <el-input
                v-model="phoneForm.phone"
                style="width: 300px"
                placeholder="请输入手机号"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updatePhone(phoneFormRef)">
              保存
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 更改性别 -->
      <div class="accountUpdate">
        <h3>更改性别</h3>
        <el-form
            ref="genderFormRef"
            :model="genderForm"
            :rules="genderRules"
            label-width="80px"
        >
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="genderForm.gender">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
              <el-radio label="保密">保密</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateGender(genderFormRef)">
              保存
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 更改密码 -->
      <div class="accountUpdate">
        <h3>更改密码</h3>
        <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
        >
          <el-form-item label="原密码" prop="oldPassword">
            <el-input
                v-model="passwordForm.oldPassword"
                style="width: 300px"
                type="password"
                placeholder="请输入原密码"
                show-password
            />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input
                v-model="passwordForm.newPassword"
                style="width: 300px"
                type="password"
                placeholder="请输入新密码"
                show-password
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
                v-model="passwordForm.confirmPassword"
                style="width: 300px"
                type="password"
                placeholder="请再次输入新密码"
                show-password
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updatePassword(passwordFormRef)">
              修改密码
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 删除账号 -->
      <div class="accountUpdate">
        <h3>删除账号</h3>
        <div class="delete-account">
          <p>删除账号后，您的所有数据将被永久清除且无法恢复</p>
          <el-button type="danger" @click="deleteAccount">
            删除账号
          </el-button>
        </div>
      </div>

      <!-- 注销账号 -->
      <div class="accountUpdate">
        <h3>注销账号</h3>
        <div class="logout-account">
          <p>注销账号后，您需要重新登录才能继续使用</p>
          <el-button type="warning" @click="logout">
            注销账号
          </el-button>
        </div>
      </div>

    </div>
  </div>
</template>

<style scoped>
/* 最外层容器 */
.body {
  padding: 20px;
}

/* 标题 */
.body h1 {
  font-size: 30px;
  margin-bottom: 30px;
  color: #333;
}

/* 主体 */
.Main {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.accountUpdate {
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}

.accountUpdate:last-child {
  border-bottom: none;
}

.accountUpdate h3 {
  margin-bottom: 15px;
  color: #666;
}

.uid-display {
  padding: 10px 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
  display: inline-block;
}

.accountUpdate p {
  color: #999;
  margin-bottom: 15px;
}

/* 注销账号样式 */
.logout-account p {
  color: #999;
  margin-bottom: 15px;
}

</style>
